package com.weituotian.moudle.front.controller;

import com.weituotian.core.controller.BaseController;
import com.weituotian.core.result.Result;
import com.weituotian.core.shiro.filter.VideoFilter;
import com.weituotian.core.utils.MultipartFileSender;
import com.weituotian.core.utils.PageInfo;
import com.weituotian.core.utils.UUIDUtils;
import com.weituotian.moudle.admin.service.IAdminVideoService;
import com.weituotian.moudle.front.entity.CommentVo;
import com.weituotian.moudle.front.entity.FrontVideo;
import com.weituotian.moudle.front.service.ICommentService;
import com.weituotian.moudle.front.service.IFrontVideoService;
import com.weituotian.moudle.member.entity.vo.VideoListVo;
import com.weituotian.moudle.member.service.IMemberService;
import com.weituotian.moudle.member.service.IPartitionService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 前台的视频页面
 * Created by ange on 2017/3/9.
 */
@Controller("frontVideoController")
@RequestMapping("${frontPath}/av")
public class VideoController extends BaseController {

    private final IPartitionService partitionService;

    private final IMemberService memberService;

    private final IFrontVideoService frontVideoService;

    private IAdminVideoService adminVideoService;

    private final ICommentService commentService;

    @Autowired
    public VideoController(IPartitionService partitionService, IMemberService memberService, IFrontVideoService frontVideoService, ICommentService commentService) {
        this.partitionService = partitionService;
        this.memberService = memberService;
        this.frontVideoService = frontVideoService;
        this.commentService = commentService;
    }

    @RequestMapping("/list")
    public String list() {
        return "";
    }


    @RequestMapping("/partitions")
    @ResponseBody
    public Object getPartitions() {
        Result result = renderSuccess("获取成功");
        result.setObj(partitionService.findAll());
        return result;
    }

    @RequestMapping("/partition_videos")
    @ResponseBody
    public Object getPartitionVideos(Integer partitionId, Integer page, Integer size) {
        PageInfo<VideoListVo> pageInfo = new PageInfo<>(page, size);
        Map<String, Object> conditions = new HashMap<>();
        conditions.put("partition", partitionId);
        pageInfo.setCondition(conditions);
        frontVideoService.findLastest(pageInfo);

        //封面相对路径转绝对路径
        for (VideoListVo vo : pageInfo.getList()) {
            vo.setCover(getCoverPath() + vo.getCover());
        }

        Result result = renderSuccess("获取成功");
        result.setObj(pageInfo);
        return result;
    }

    /*@RequestMapping("{id}")
    @ResponseBody
    public Object getVideoInfo(@PathVariable("id") Integer id) {
        FrontVideo frontVideo = frontVideoService.findFrontVideo(id);
        return frontVideo;
    }*/

    /**
     * 根据id获得视频详细信息
     *
     * @param id
     * @return
     */
    @RequestMapping(value = "/info", produces = "application/json; charset=utf-8")
    @ResponseBody
    public Object getVideoInfo(Integer videoId) {
        FrontVideo frontVideo = null;
        try {
            frontVideo = frontVideoService.findFrontVideo(videoId);
            frontVideo.setCover(getCoverPath() + frontVideo.getCover());
            frontVideo.setMemberCover(getAvatarPath() + frontVideo.getMemberCover());


        } catch (Exception e) {
            e.printStackTrace();
            return renderError(e.getMessage());
        }
        Result result = renderSuccess("获取成功");
        result.setObj(frontVideo);
        return result;
    }

    /**
     * 获得视频url,同时播放+1
     *
     * @param videoId 视频id
     * @param token   token
     * @return
     */
    @RequestMapping(value = "/getSrc", produces = "application/json; charset=utf-8")
    @ResponseBody
    public Object getVideoSrc(Integer videoId, String token) {
        String filename = null;
        try {
            filename = frontVideoService.getVideoPath(videoId, token);
        } catch (Exception e) {
            e.printStackTrace();
            return renderError("not found!");
        }
        Result result1 = renderSuccess("获取成功");

        //生成uuid
        Session session = SecurityUtils.getSubject().getSession();
        String uuid = UUIDUtils.getUUID();
        session.setAttribute(VideoFilter.VIDEO_KEY, uuid);

        String path = getVideoPath() + filename + "?token=" + uuid;
        result1.setObj(path);
        return result1;
    }

    @RequestMapping(value = "/getSrc2", produces = "video/mp4")
//    @ResponseBody
    public void getVideoSrc2(Integer videoId, HttpSession session, HttpServletResponse response) {
        String filename = frontVideoService.getVideoPath(videoId, "asd");
        String fullpath = videoPath + "/" + filename;
        String realpath = session.getServletContext().getRealPath(fullpath);
        File file = new File(realpath);

        InputStream in = null;
        ServletOutputStream out = null;
        try {
            in = new FileInputStream(file);
            response.setContentType("video/mp4");
            out = response.getOutputStream();
            byte[] buffer = new byte[4 * 1024];
            int length;
            while ((length = in.read(buffer)) > 0) {
                out.write(buffer, 0, length);
            }
        } catch (FileNotFoundException e) {
            System.out.println("文件读取失败,文件不存在");
            e.printStackTrace();
        } catch (IOException e) {
            System.out.println("文件流输出异常");
            e.printStackTrace();
        } finally {
            try {
                if (in != null) {
                    in.close();
                }
                if (out != null) {
                    out.close();
                }
            } catch (IOException e) {
                System.out.println("文件流关闭异常");
                e.printStackTrace();
            }
        }

    }

    @RequestMapping(value = "/getSrc3", produces = "video/mp4")
    @ResponseBody
    public FileSystemResource getVideoSrc3(Integer videoId, HttpSession session, HttpServletResponse response) {
        String filename = frontVideoService.getVideoPath(videoId, "asd");
        String fullpath = videoPath + "/" + filename;
        String realpath = session.getServletContext().getRealPath(fullpath);
        File file = new File(realpath);
        return new FileSystemResource(file);
    }

    @RequestMapping(value = "/getSrc4", produces = "video/mp4")
    public void getVideoSrc4(Integer videoId, HttpSession session, HttpServletRequest request, HttpServletResponse response) {
        String filename = frontVideoService.getVideoPath(videoId, "asd");
        String fullpath = videoPath + "/" + filename;
        String realpath = session.getServletContext().getRealPath(fullpath);
        File file = new File(realpath);

        try {
            MultipartFileSender.fromPath(file.toPath())
                    .with(request)
                    .with(response)
                    .serveResource();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获得视频的评论,分页
     *
     * @param videoId 视频ID
     * @param page    页数
     * @param size    页面大小
     * @return
     */
    @RequestMapping(value = "/comments", produces = "application/json; charset=utf-8")
    @ResponseBody
    public Object getComments(Integer videoId, Integer page, Integer size) {
        PageInfo<CommentVo> pageInfo = new PageInfo<>(page, size);
        List<CommentVo> commentVos = commentService.getCommentVos(videoId, pageInfo);

        int max = pageInfo.getTotal() - pageInfo.getFrom();
        for (CommentVo commentVo : commentVos) {
            commentVo.setUserAvatar(getAvatarPath() + commentVo.getUserAvatar());
            commentVo.setFloor(max);
            max--;
        }
        pageInfo.setList(commentVos);

        Result result = renderSuccess("获取成功");
        result.setObj(pageInfo);
        return result;
    }

    /**
     * 搜索功能
     * @param page
     * @param size
     * @return
     */
    @RequestMapping(value = "/search", produces = "application/json; charset=utf-8")
    @ResponseBody
    public Object search(Integer page, Integer size) {
        PageInfo<VideoListVo> pageInfo = new PageInfo<>(page, size);


        //条件
        pageInfo.setCondition(getSearchMap());

        pageInfo.addSort("createTime", "asc");

//        adminVideoService.findPage(pageInfo);

        frontVideoService.findLastest(pageInfo);

        //封面相对路径转绝对路径
        for (VideoListVo vo : pageInfo.getList()) {
            vo.setCover(getCoverPath() + vo.getCover());
        }

        Result result = renderSuccess("获取成功");
        result.setObj(pageInfo);
        return result;
    }
}
